package nil.ed.livechat.timeshift.sync.ext;

import com.alibaba.fastjson.JSON;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import nil.ed.livechat.timeshift.sync.common.RedisKeys;
import nil.ed.livechat.timeshift.utils.m3u8.TsInfo;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author delin10
 * @since 2020/6/26
 **/
@Slf4j
public class RedisSyncService {

    @Inject
    private JedisPool pool;

    private Thread subscribedThread;

    @Inject
    private PublishEventSubscriber subscriber;

    public void push(TsInfo tsInfo) {
        Jedis jedis = pool.getResource();
        jedis.rpush(RedisKeys.SYNC_TS_LIST.getKeyWithTemplate(tsInfo.getName()), JSON.toJSONString(tsInfo));
        jedis.close();
    }

    public void clear(String name) {
        Jedis jedis = pool.getResource();
        jedis.del(RedisKeys.SYNC_TS_LIST.getKeyWithTemplate(name));
        jedis.close();
    }

    public void startSubscribe() {
        this.subscribedThread = new Thread(() -> {
            try (Jedis jedis = pool.getResource()) {
                log.info("开始订阅...");
                jedis.subscribe(subscriber, RedisKeys.PUBLISH_TOPIC.getRawKey());
            } catch (Exception e) {
                log.error("订阅发生错误", e);
                System.exit(-1);
            }
        });
        this.subscribedThread.setDaemon(true);
        this.subscribedThread.start();
    }
}
